package com.lego.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lego.bean.User;
import com.lego.service.UserService;
import com.lego.service.impl.UserServiceImpl;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		UserService us = new UserServiceImpl();
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String userName = request.getParameter("uName");
		String password = request.getParameter("uPwd");
		//保存账号密码
		String autoSave = request.getParameter("autoSave");
		if("on".equals(autoSave)){
			Cookie cookie = new Cookie("uname",userName);
			Cookie cookie2 = new Cookie("upwd",password);
			cookie.setMaxAge(60*60*24*7);
			cookie2.setMaxAge(60*60*24*7);
			response.addCookie(cookie);
			response.addCookie(cookie2);
		}else{
			Cookie cookie = new Cookie("uname","");
			Cookie cookie2 = new Cookie("upwd","");
			cookie.setMaxAge(0);
			cookie2.setMaxAge(0);
			response.addCookie(cookie);
			response.addCookie(cookie2);
		}
		User user = us.loginUser(userName, password);
		if(user!=null){
			session.setAttribute("loginUser", user);
			response.sendRedirect("index.jsp");
		}else{
			request.setAttribute("msg","用户不存在或密码错误");
			request.getRequestDispatcher("login.jsp").forward(request,response);
		}
	}

}
